package com.mlc.core.serviceImpl;

import com.mlc.core.common.QueryUtil;
import com.mlc.core.dto.RequestDto;
import com.mlc.core.service.PlaylistsService;
import com.mlc.data.dao.DetailsDao;
import com.mlc.data.dao.PlaylistsDao;
import com.mlc.data.dao.SongsDao;
import com.mlc.data.entity.Playlists;
import com.mlc.data.entity.Songs;
import com.mlc.utils.commom.ConvUtil;
import lombok.AllArgsConstructor;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author FireWang
 * @date 2022/03/14 02:46:46
 */
@Service
@AllArgsConstructor
@Transactional
public class PlaylistsServiceImpl implements PlaylistsService {
    private PlaylistsDao playlistsDao;
    private SongsDao songsDao;
    private DetailsDao detailsDao;

    @Override
    public List<Playlists> getAll() {
        return playlistsDao.findAll();
    }

    @Override
    public Playlists getById(Integer id) {
        Optional<Playlists> playlists = playlistsDao.findById(id);
        return playlists.get();
    }

    @Override
    public void insert(Playlists playlists) {
        playlists.setCreateTime(new Date());
        playlistsDao.save(playlists);
    }

    @Override
    public void update(Playlists playlists) {
        playlists.setModifyTime(new Date());
        playlistsDao.save(playlists);
    }

    @Override
    public void deleteById(Integer id) {
        playlistsDao.deleteById(id);
    }

    @Override
    public List getPlayListByCondition(RequestDto playListDto) throws Exception {

        //创建查询条件工具类
        QueryUtil query = new QueryUtil();

        //构造查询条件
        Specification<Songs> queryCondition;

        /**
         *  playlistType:
         *  0-默认歌单；查所有歌曲
         *  1-用户歌单；查用户歌单（唯一）
         */
        if (ConvUtil.convToInt(playListDto.getPlaylistType()) == 1) {
            /**用户歌单
             * 1、歌单表（playlists）：根据userId查到歌单Id即playId
             * 2、点歌详情表（details）:然后根据playId查询songId列表
             * 3、歌曲表（songs）:根据songId列表和条件查询歌曲详情
             */
            Integer playId = playlistsDao.findIdByUserId(playListDto.getUserId());
            List<Integer> songIdList = detailsDao.findSongIdByPlayId(playId);
            queryCondition = (root, criteriaQuery, criteriaBuilder) -> {
                //初始化条件参数
                query.init(root, criteriaQuery, criteriaBuilder);
                //拼接条件
                query.in("id", songIdList);
                QueryUtil.commonQuery(query, playListDto);
                //获取条件列表
                List<Predicate> predicateList = query.getPredicateList();
                //获取完整条件体
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            };
        } else {
            //默认歌单：即系统歌单，直接查询songs（歌曲表）
            queryCondition = (root, criteriaQuery, criteriaBuilder) -> {
                //初始化条件参数
                query.init(root, criteriaQuery, criteriaBuilder);
                //拼接条件
                QueryUtil.commonQuery(query, playListDto);
                //获取条件列表
                List<Predicate> predicateList = query.getPredicateList();
                //获取完整条件体
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            };
        }
        return songsDao.findAll(queryCondition, query.getPage(playListDto).getPageable()).getContent();
    }
}